import { defineStore } from 'pinia'
import axios from 'axios'

// 创建 axios 实例
const api = axios.create({
  baseURL: 'http://1.14.10.129:8081',
  timeout: 5000
})

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: JSON.parse(localStorage.getItem('user')) || null,
    token: localStorage.getItem('token') || null
  }),
  
  actions: {
    async login(username, password) {
      try {
        const response = await api.post('/login', {
          username,
          password
        })
        
        const { data } = response
        this.user = { username }
        this.token = data.token
        
        // 持久化存储
        localStorage.setItem('user', JSON.stringify(this.user))
        localStorage.setItem('token', this.token)
        
        // 设置后续请求的默认 token
        api.defaults.headers.common['Authorization'] = `Bearer ${this.token}`
      } catch (error) {
        console.error('登录错误:', error)
        throw error
      }
    },

    logout() {
      this.user = null
      this.token = null
      localStorage.removeItem('user')
      localStorage.removeItem('token')
      // 清除 axios 默认 header
      delete api.defaults.headers.common['Authorization']
    }
  }
}) 